//
//  ATCommentViewController.m
//  Adorable_Things
//
//  Created by huzhiyan on 16/1/15.
//  Copyright © 2016年 Banana Inc. All rights reserved.
//

#import "ATCommentViewController.h"
#import "ATCommentFootView.h"
#import "ATDetailThirdSectionTableViewCell.h"
#import "ArticleDetailCommentModel.h"
#import "ATLoginViewController.h"

@interface ATCommentViewController () <UITableViewDataSource,UITableViewDelegate, UITextFieldDelegate>

@property (nonatomic, strong) ATCommentFootView *footView;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) CGRect newFrame;
@property (nonatomic, assign) CGRect oldFrame;

@end

@implementation ATCommentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // 键盘高度255
    [self addSubTableViewAndFootView];
    
    _dataArr = [NSMutableArray array];
    
    _oldFrame = CGRectMake(0, kHeight - 50 - 65, kWidth, 50);
    _newFrame = CGRectMake(0, kHeight - 360, kWidth, 50);
    
    // 下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        _page = 0;
        [self setUpData];
    }];
    
}

- (void)addSubTableViewAndFootView
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight - 50 - 65) style:(UITableViewStylePlain)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.rowHeight = 100;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    [_tableView registerNib:[UINib nibWithNibName:@"ATDetailThirdSectionTableViewCell" bundle:nil] forCellReuseIdentifier:@"ATDetailThirdSectionTableViewCell"];
    
    _footView = [[[UINib nibWithNibName:@"ATCommentFootView" bundle:nil] instantiateWithOwner:self options:nil] lastObject];
    _footView.frame = CGRectMake(0, kHeight - 50 - 65, kWidth, 50);
    [self.view addSubview:_footView];
    
    _footView.commentTF.delegate = self;
    _footView.commentTF.clearButtonMode = UITextFieldViewModeAlways;
    _footView.commentTF.userInteractionEnabled = YES;
    
    [_footView.commentBT addTarget:self action:@selector(commentBTClick:) forControlEvents:(UIControlEventTouchUpInside)];
}

- (void)setUpData
{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"page"] = [NSString stringWithFormat:@"%ld", (long)_page];
    parDic[@"page_size"] = @"20";
    parDic[@"topic_id"] = self.post_ID;
    parDic[@"topic_type"] = self.topic_ID;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:@"http://api.menghuoapp.com/v1/comment/list" parameters:parDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSArray *dataArray = responseObject[@"data"];
        if (_page == 0) {
            [_dataArr removeAllObjects];
        }
        for (NSDictionary *oneDic in dataArray) {
            ArticleDetailCommentModel *model = [[ArticleDetailCommentModel alloc] init];
            [model setValuesForKeysWithDictionary:oneDic];
            [_dataArr addObject:model];
        }
        [self.tableView.mj_header endRefreshing];
        [_tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败");
    }];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ATDetailThirdSectionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ATDetailThirdSectionTableViewCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    ArticleDetailCommentModel *model = _dataArr[indexPath.row];
    [cell.iconImageView sd_setImageWithURL:[NSURL URLWithString:model.user[@"avatar"]]];
    cell.iconImageView.layer.masksToBounds = YES;
    cell.iconImageView.layer.cornerRadius = 30;
    cell.nameLabel.text = model.user[@"nickname"];
    cell.nameLabel.font = [UIFont systemFontOfSize:14];
    cell.contentLabel.text = model.content;
    cell.contentLabel.font = [UIFont systemFontOfSize:14];
    [cell.likeButton setImage:[UIImage imageNamed:@"iconfont-zan"] forState:(UIControlStateNormal)];
    [cell.likeButton addTarget:self action:@selector(likeButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    cell.likeLabel.text = [NSString stringWithFormat:@"%@", model.like_num];
    return cell;
}

- (void)commentBTClick:(UIButton *)button
{
    ATUserManager *manager = [ATUserManager shareManager];
    if (self.footView.commentTF.text.length != 0) {
        NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
        parDic[@"auth_token"] = manager.auth_token;
        parDic[@"content"] = self.footView.commentTF.text;
        parDic[@"topic_id"] = self.post_ID;
        parDic[@"topic_type"] = self.topic_ID;
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        [manager POST:@"http://api.menghuoapp.com/v1/comment/add" parameters:parDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"提交成功");
            [self setUpData];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"提交失败");
        }];
    } else {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"评论不能为空哦！" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
        [alertView show];
    }
}

- (void)likeButtonClick:(UIButton *)button
{
    ATUserManager *atManager = [ATUserManager shareManager];
    ATDetailThirdSectionTableViewCell *cell = (ATDetailThirdSectionTableViewCell *)[[button superview] superview];
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    ArticleDetailCommentModel *model = self.dataArr[indexPath.row];
    if (atManager.isLogin == 1) {
        NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
        parDic[@"auth_token"] = atManager.auth_token;
        parDic[@"comment_id"] = [NSString stringWithFormat:@"%@", model.comment_id];
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        [manager POST:@"http://api.menghuoapp.com/v1/comment/like" parameters:parDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSInteger index = [model.like_num integerValue];
            index -= index;
            cell.likeLabel.text = [NSString stringWithFormat:@"%ld", index];
            [self setUpData];
            NSLog(@"成功点赞");
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"点赞失败");
        }];
    }else{
        ATLoginViewController *loginVC = [[ATLoginViewController alloc] init];
        UINavigationController *loginNavC = [[UINavigationController alloc] initWithRootViewController:loginVC];
        loginNavC.navigationBarHidden = YES;
        [self presentViewController:loginNavC animated:YES completion:nil];
    }
    atManager.isLogin = 1;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    self.footView.frame = _newFrame;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    self.footView.frame = _oldFrame;
    [textField resignFirstResponder];
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
